<template>
  <div :key="componentsKey" class="charge_list">
    <div v-if="calcEntry.charges && calcEntry.charges.length">
      <div v-for="(item, index) in chargesFormat" :key="index" class="gl_mb_10" :class="isUseShadow ? 'gameEntry_shadow' : ''">
        <el-row class="gl_py_5" type="flex" justify="space-between">
          <el-col :span="20">
            <span class="charge_item_title gl_mr_20">{{ item.name }}</span>
            <!-- <span v-if="!calcEntry.isFree" class="charge_item_amount">{{ item.name }} {{ formatMoney(item.unitAmount) }} 元</span> -->
          </el-col>
          <el-col v-if="isShowCtrlBtn" :span="4" align="right">
            <el-button v-if="item.code === 'Entry'" size="mini" @click="entryToEdit">去修改</el-button>
          </el-col>
        </el-row>
        <el-table :data="item.items" size="mini">
          <!-- 通用-序号 -->
          <el-table-column type="index" label="序号" align="center" width="50" />
          <!-- 通用-姓名 -->
          <el-table-column prop="name" label="姓名" />
          <!-- 性别 -->
          <el-table-column v-if="hasColumn(item.code, 'gender')" prop="gender" label="性别" align="center" width="60" />
          <!-- 证件号码 -->
          <el-table-column v-if="hasColumn(item.code, 'idCardNumber')" prop="idCardNumber" label="证件号码" />
          <el-table-column v-if="hasColumn(item.code, 'simultaneousEntryAmount')" prop="simultaneousEntryAmount" label="兼项费">
            <template slot-scope="{row}">
              <p>{{ formatMoney(row.amount) }}</p>
            </template>
          </el-table-column>
          <!-- 参赛机构 -->
          <el-table-column v-if="hasColumn(item.code, 'organization')" prop="organization" label="参赛机构" />
          <!-- 参报赛区 -->
          <template v-if="gameInfo.isFinal">
            <el-table-column v-if="hasColumn(item.code, 'subCompetitionName')" prop="subCompetitionName" label="参报赛区" />
          </template>
          <el-table-column v-if="hasColumn(item.code, 'entryAmount')" prop="entryAmount" label="报名费">
            <template slot-scope="{row}">
              <p>{{ formatMoney(row.amount) }}</p>
            </template>
          </el-table-column>
          <!-- 所报项目(大团体) -->
          <el-table-column v-if="hasColumn(item.code, 'eventName')" prop="eventName" label="所报项目">
            <template slot-scope="scope">
              <span>{{ scope.row.event.eventCategoryName }} </span>
              <!-- <span>{{ scope.row.event.eventGroupName }}</span>
              <span>{{ scope.row.event.eventShortName }}</span>
              <span v-if="scope.row.event.teamNo">{{ scope.row.event.teamNo }}组</span> -->
            </template>
          </el-table-column>
          <!-- 参赛组(大团体) -->
          <el-table-column v-if="hasColumn(item.code, 'teamName')" label="参赛组">
            <template slot-scope="scope">
              <span>{{ scope.row.event.genderName }}</span>
              <span v-if="scope.row.event.teamNo">{{ scope.row.event.teamNo }}组</span>
            </template>
          </el-table-column>
          <!-- 个人项目 -->
          <el-table-column v-if="hasColumn(item.code, 'individualEvents')" prop="individualEvents" label="个人项目">
            <template slot-scope="{row}">
              <div v-for="(ntem, n) in row.individualEvents" :key="n" class="event_border gl_ellipsis">
                <el-tooltip :content="ntem.eventCategoryName + ntem.eventGroupName + ntem.eventShortName" placement="left" effect="light">
                  <p class="gl_ellipsis">
                    <span>{{ ntem.eventCategoryName }} </span>
                    <span>{{ ntem.eventGroupName }}</span>
                    <span>{{ ntem.eventShortName }}</span>
                  </p>
                </el-tooltip>
              </div>
            </template>
          </el-table-column>
          <!-- 团体项目 -->
          <el-table-column v-if="hasColumn(item.code, 'teamEvents') && isShowTeamEvents" prop="teamEvents" label="团体项目">
            <template slot-scope="{row}">
              <div v-for="(ntem, n) in row.teamEvents" :key="n" class="event_border">
                <el-tooltip :key="index" :content="ntem.eventCategoryName + ntem.eventGroupName + ntem.eventShortName + `${ntem.weightClass ? ' (' + ntem.weightClass.name + ') ' : '' }` + `${ntem.teamNo ? ntem.teamNo + '组' : '' }`" placement="left" effect="light">
                  <p class="gl_ellipsis">
                    <span>{{ ntem.eventCategoryName }} </span>
                    <span>{{ ntem.eventGroupName }}</span>
                    <span>{{ ntem.eventShortName }}</span>
                    <span v-if="ntem.weightClassName"> ({{ ntem.weightClassName }})</span>
                    <span v-if="ntem.teamNo"> {{ ntem.teamNo }}组</span>
                  </p>

                </el-tooltip>
              </div>
            </template>
          </el-table-column>
          <!-- 共报项目(兼项) -->
          <el-table-column v-if="hasColumn(item.code, 'totalEventCount')" prop="totalEventCount" label="共报项目" align="center">
            <template slot-scope="scope">
              <span>{{ scope.row.totalEventCount }}</span>
            </template>
          </el-table-column>
          <!-- 产生兼项费(兼项) -->
          <el-table-column v-if="hasColumn(item.code, 'exceedCount')" prop="exceedCount" label="产生兼项费" align="center">
            <template slot-scope="scope">
              <span>{{ scope.row.exceedCount }}</span>
            </template>
          </el-table-column>
          <!-- 保险 -->
          <el-table-column v-if="hasColumn(item.code, 'hasInsurance')" prop="amount" label="是否购买保险" align="center">
            <template slot-scope="scope">
              <el-checkbox :value="scope.row.hasInsurance" :disabled="!scope.row.canChange" @change="changeInsurance(scope.row)" />
            </template>
          </el-table-column>
          <!-- 脚套 -->
          <el-table-column v-if="hasColumn(item.code, 'needFootCover')" prop="needFootCover" label="是否需要赛事方提供脚套" align="center">
            <template slot-scope="scope">
              <el-checkbox :value="scope.row.needFootCover" :title="scope.row.canChange ? '' : '报名的项目不允许修改'" :disabled="!scope.row.canChange" @change="changeNeedFootCover(scope.row)" />
            </template>
          </el-table-column>
          <!-- 脚码 -->
          <el-table-column v-if="hasColumn(item.code, 'footSize')" prop="footSize" label="脚码数(cm)" align="center">
            <template slot-scope="scope">
              <el-input-number
                :key="scope.row.footSize"
                :title="!scope.row.canChange && !scope.row.needFootCover ? '无需脚套，不可修改' : ''"
                :value="scope.row.footSize"
                :disabled="!scope.row.canChange && !scope.row.needFootCover"
                class="gl_mr_10"
                size="mini"
                placeholder="脚码"
                :controls="false"
                :style="{width:'80px'}"
                :min="0"
                :max="99"
                @blur="changeFootSize(scope.row)"
                @change="onInputFootSize($event, scope.row)"
              />
            </template>
          </el-table-column>
          <!-- 费用 -->
          <el-table-column v-if="hasColumn(item.code, 'amount')" prop="amount" label="费用(元)" align="center">
            <template slot-scope="scope">
              <span>{{ formatMoney(scope.row.amount) }}</span>
            </template>
          </el-table-column>
        </el-table>
        <el-row v-if="!calcEntry.isFree" class="sub_total gl_py_5" type="flex" justify="end">
          <el-col :span="6" align="right">
            <span v-if="subTotal[item.code].text">{{ subTotal[item.code].text }} {{ item.itemsCount }} {{ subTotal[item.code].unit }}</span>
          </el-col>
          <el-col :span="6" align="right">
            <span>合计：<span class="gl_ft_weight">{{ formatMoney(item.categoryAmount) }}</span> 元</span>
          </el-col>
        </el-row>
      </div>
    </div>

    <template v-if="calcEntry.summary && calcEntry.summary.length && !calcEntry.isFree">
      <el-row class="summary_wrap gameEntry_shadow">
        <template v-for="(item, index) in calcEntry.summary">
          <el-col :key="index" :span="8">
            <ul class="summary_list">
              <li class="summary_item gl_clear">
                <span class="summary_item_title gl_fl">{{ item.chargeTypeName }}：</span>
                <span class="gl_fl">{{ formatMoney(item.amount) }} 元</span>
              </li>
            </ul>
          </el-col>
        </template>
        <el-col :span="24" class="gl_pt_10">
          <ul class="summary_list">
            <li class="summary_item summary_total gl_clear">
              <span class="summary_item_title gl_fl">已缴纳费用：</span>
              <span class="gl_fl">{{ formatMoney(calcEntry.paidAmount) }} 元</span>
            </li>
            <li class="summary_item summary_total gl_clear">
              <span class="summary_item_title gl_fl">合计：</span>
              <span class="gl_fl">{{ formatMoney(calcEntry.totalAmount - calcEntry.paidAmount) }} 元</span>
            </li>
          </ul>
        </el-col>
      </el-row>
    </template>
  </div>
</template>

<script>
import {
  api_PUT_EventsManagementEntryComRegisterInsuranceCompetitionRegisterId, // 14-设置是否收保险
  api_PUT_EventsManagementEntryComRegisterFootCompetitionRegisterId // 15-设置脚码
} from '@/extend/api/gameswaggerApi/app.js';

export default {
  props: {
    calcEntry: {
      type: Object,
      default () {
        return {};
      }
    },
    entryType: {
      type: String,
      default: ''
    },
    isShowCtrlBtn: {
      type: Boolean,
      default: true
    },
    gamefree: {
      type: Boolean,
      default: true
    },
    gameInfo: {
      type: Object,
      default () {
        return {};
      }
    },
    isUseShadow: {
      type: Boolean,
      default: false
    }
  },
  data () {
    return {
      // BigTeam 大团体; Foot 脚套费; Entry 报名费; SimultaneousEntry 兼项费; Deposit 保证金; Insurance 保险费; Custom 自定义;
      columnMap: {
        BigTeam: {
          organization: true,
          eventName: true, // 所报项目
          teamName: true // 参赛组数
        },
        Foot: {
          gender: true,
          idCardNumber: true,
          organization: true,
          needFootCover: true, // 是否需要赛事方提供脚套
          footSize: true // 脚码数
        },
        Entry: {
          gender: true,
          idCardNumber: true,
          organization: true,
          entryAmount: true,
          subCompetitionName: true,
          individualEvents: true,
          teamEvents: true
        },
        SimultaneousEntry: {
          gender: true,
          idCardNumber: true,
          simultaneousEntryAmount: true,
          organization: true,
          totalEventCount: true, // 共报项目
          exceedCount: true // 产生兼项费
        },
        Deposit: {
          gender: true,
          idCardNumber: true,
          organization: true
        },
        Insurance: {
          idCardNumber: true,
          hasInsurance: true // 是否购买保险
        },
        Custom: {
          gender: true,
          idCardNumber: true,
          organization: true
        }
      },
      subTotal: {
        BigTeam: { text: '产生大团体费用：', unit: '次' },
        Foot: { text: '电子脚套费：', unit: '人' },
        Entry: { text: '共报名人数为：', unit: '人' },
        SimultaneousEntry: { text: '产生兼项费为：', unit: '次' },
        Deposit: { text: '保证金人数为：', unit: '人' },
        Insurance: { text: '产生保险费为：', unit: '次' },
        Custom: { text: '', unit: '' }
      },
      changeFootLoading: false // 防止触发两次请求
    };
  },
  computed: {
    chargesFormat() {
      return this.calcEntry.charges.map(item => {
        if (item.code === 'Foot') {
          for (let j = 0; j < item.items.length; j++) {
            const jtem = item.items[j];
            jtem.$footSize = jtem.footSize;
            jtem.$isShowSave = false;
          }
        }
        return item;
      });
    },
    componentsKey() {
      return this.calcEntry.charges ? String(this.calcEntry.charges.length) + Math.random() : String(Math.random());
    },
    isShowTeamEvents() {
      return this.entryType !== 'Personal';
    }
  },
  methods: {
    // 格式化货币格式 （分）
    formatMoney(num) {
      if (typeof num === 'number' && !Number.isNaN(num)) {
        // num 是数字类型 且不是 NaN
        let strNum = String(num); // 金额文本类型
        if (num >= 0) {
          strNum = strNum.padStart(3, '0'); // 用0填充保证最小三位数
          return strNum.slice(0, -2) + '.' + strNum.slice(-2); // 金额拼接
        } else {
          const _mark = strNum.slice(0, 1); // 负号
          const _noMark = strNum.slice(1); // 无负号数值
          strNum = _noMark.padStart(3, '0'); // 用0填充保证最小三位数
          return _mark + strNum.slice(0, -2) + '.' + strNum.slice(-2); // 金额拼接
        }
      } else {
        return '';
      }
    },
    // 是否被忽略
    hasColumn (chargeCode, tableProp) {
      return this.columnMap[chargeCode][tableProp];
    },
    entryToEdit() {
      this.$emit('onEntryEdit');
    },
    reGetCharges() {
      this.$emit('onReGetCharges');
    },
    // 改变保险
    changeInsurance (item) {
      const vo = {
        hasInsurance: !item.hasInsurance
      };
      this.comRegisterInsuranceApi(item.id, vo);
    },
    // 改变保险API
    comRegisterInsuranceApi(id, vo) {
      api_PUT_EventsManagementEntryComRegisterInsuranceCompetitionRegisterId(id, vo)
        .then(
          res => {
            this.$message({
              message: `保险修改成功`,
              type: 'success',
              showClose: true
            });
            this.reGetCharges();
          }
        )
        .catch(
          error => {
            this.$message({
              message: `保险修改失败 ${error.error.message}`,
              type: 'error',
              showClose: true
            });
          }
        );
    },
    // 脚码输入处理
    onInputFootSize (value, data) {
      data.$footSize = value;
    },
    // 是否需要赛事方提供脚套
    changeNeedFootCover (item) {
      if (this.changeFootLoading === false) {
        if (typeof item.$footSize === 'number' && item.$footSize > 0) {
          const vo = {
            footSize: item.needFootCover ? 0 : item.$footSize
          };
          console.log('vo: ', vo);
          this.comRegisterFootApi(item.id, vo);
        } else {
          // 用户不想写脚码，根据产品需求调整为填入默认值1
          this.comRegisterFootApi(item.id, {
            footSize: 1
          });
          // this.$message({
          //   message: `请输入脚码数`,
          //   type: 'warning',
          //   showClose: true
          // });
        }
      }
    },
    // 改变脚码
    changeFootSize (item) {
      if (item.$footSize !== item.footSize) {
        if (typeof item.$footSize === 'number') {
          const vo = {
            footSize: item.$footSize
          };
          this.comRegisterFootApi(item.id, vo);
        } else {
          this.$message({
            message: `请输入脚码数`,
            type: 'warning',
            showClose: true
          });
          item.footSize = item.$footSize;
        }
      }
    },
    // 改变脚码
    comRegisterFootApi(id, vo) {
      this.changeFootLoading = true;
      api_PUT_EventsManagementEntryComRegisterFootCompetitionRegisterId(id, vo)
        .then(
          res => {
            this.$message({
              message: `修改成功`,
              type: 'success',
              showClose: true
            });
            this.reGetCharges();
            this.changeFootLoading = false;
          }
        )
        .catch(
          error => {
            this.$message({
              message: `修改失败 ${error.error.message}`,
              type: 'error',
              showClose: true
            });
            this.reGetCharges();
            this.changeFootLoading = false;
          }
        );
    }
  }
};
</script>

<style>
.charge_list .el-table,
.charge_list .el-table__body-wrapper {
  min-height: auto;
}
</style>

<style scoped>
.sub_total {
  font-size: 14px;
}

.charge_item_title {
  display: inline-block;
  vertical-align: middle;
  min-width: 70px;
  font-size: 16px;
  line-height: 24px;
  font-weight: bold;
}
.charge_item_amount {
  font-size: 14px;
  font-weight: normal;
}

.summary_wrap {
  padding-bottom: 20px;
}
.summary_item.summary_total {
  font-weight: bold;
}
.summary_item {
  font-size: 14px;
  line-height: 24px;
}
.summary_item_title {
  min-width: 100px;
}

.event_border {
  padding: 2px 0;
  border-bottom: 1px solid #dfe6ec;
}
.event_border:last-child{
  border-bottom: none;
}

.gameEntry_shadow {
  padding: 12px;
  border-radius: 8px;
  background-color: #fff;
  box-shadow: 0px 10px 36px 0px rgba(0,0,0,0.08);
}
</style>
